package org.fatewa.engine.advice.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.fatewa.engine.advice.protocol.RayquazaResponse;
import org.fatewa.engine.design.advice.AbstractProtocolMapper;
import org.fatewa.engine.property.RayquazaResponseProperties;
import org.fatewa.engine.utils.MultipartDataOrderPlugin;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;

import java.lang.reflect.Method;

/**
 * 默认的分页映射
 * 关于映射器，详见 {@link AbstractProtocolMapper}
 * @author 4everlynn
 */
public class PagingDataMapper extends AbstractProtocolMapper<IPage<?>> {

    @Override
    public RayquazaResponse map(IPage<?> body, Method method, RayquazaResponseProperties properties, JacksonProperties jackson) {
        RayquazaResponse rayquazaResponse = new RayquazaResponse();

        rayquazaResponse
                .code(properties.getCodeMapper().getSuccess())
                .msg(properties.getMessageMapper().getSuccess());

        // 获取到配置的 Key
        String key = properties.getDataKey();
        // 将 Response 放置到对应 key 下
        rayquazaResponse.include(key, body.getRecords());
        // 输入所有内容
        rayquazaResponse.parties(body);

        if (body.getSize() < 0) {
            int size = body.getRecords().size();
            rayquazaResponse.include("total", size);
            rayquazaResponse.exclude("size");
            body.setTotal(size);
            body.setSize(size);
        }

        // 去除无用字段
        rayquazaResponse.retain("msg", "code", "total", "size", "current", key, "pages");
        rayquazaResponse.include("pages", body.getPages());
        // 对字段进行排序
        MultipartDataOrderPlugin plugin = new MultipartDataOrderPlugin();
        plugin.install(rayquazaResponse);
        plugin.ordered("msg", "code", key, "current", "total", "size", "pages");

        // 返回处理后的结果
        return rayquazaResponse;
    }

}

